package com.zhixianggou.caibaobox.user.shiro.filter;


import com.zhixianggou.caibaobox.commons.result.ReturnCodeEnum;
import com.zhixianggou.caibaobox.commons.result.ReturnData;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Service;


import java.io.PrintWriter;
import java.util.HashMap;

/**
 * Created by bxl on 2018/1/22.
 */
@SuppressWarnings("unchecked")
@Service
public class MyShiroAjaxTimeoutFilter
        extends FormAuthenticationFilter
{

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        if (this.isLoginRequest(request, response)) {
//            if (this.isLoginSubmission(request, response)) {
//                return this.executeLogin(request, response);
//            } else {
//                return true;
//            }
//        } else {
//            if (isAjax(request)) {
//                HashMap item = new HashMap();
//                item.put("code", "-1");
//                item.put("msg", "登录超时或过期，请重新登录！");
//                response.setContentType("application/json;charset=UTF-8");
//                ((HttpServletResponse) response).setStatus(403);
//                response.getWriter().print(JSON.toJSONString(item));
//
//            } else {
//                this.saveRequestAndRedirectToLogin(request, response);
//            }
//            return false;
//        }
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");

        PrintWriter out = httpServletResponse.getWriter();
        out.println(ReturnData.fail(ReturnCodeEnum.UN_LOGIN));
        out.flush();
        out.close();
        return false;
    }
    public static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
//            logger.debug("当前请求为Ajax请求");
            return Boolean.TRUE;
        }
//        logger.debug("当前请求非Ajax请求");
        return Boolean.FALSE;
    }
}
